package com.af.dao.mobile.impl;

import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.af.common.CommonUtil;
import com.af.common.DBHelper;
import com.af.common.GlobalVariables;
import com.af.common.Log4jXmlConfig;
import com.af.common.PropertiesManager;
import com.af.dao.mobile.IMobileNotice;
import com.af.dao.pay.IPayToApi;
import com.af.dao.pay.PayEntity;
import com.af.dao.pay.impl.PayToApi;
import com.af.entity.mobile.MobilePar;
import com.af.entity.mobile.Order;

public class MobileNotice implements IMobileNotice {

	Logger LOG = Log4jXmlConfig.getInstance().returnLogger(MobileNotice.class);
	
	
	@Override
	public void getMobileNotice(HttpServletRequest request) {
		// TODO Auto-generated method stub
		
		ReturnState rs = null;
		
		Map map = new CommonUtil().returnParamMap(request);
		
		int status = Integer.valueOf(map.get("status").toString());

		Order order = searchOrder(map.get("orderid").toString());

		// 实际完成金额
		order
				.setRealPrice(Double.parseDouble(map.get("ordermoney")
						.toString()));
		int state = status;

		if (status == 9) {
			state = 4;
			order.setLastState(state);
		}else{
			// 通过服务确认订单
			
			rs = new ReturnState();
			
			Order newOrder = rs.returnLastOrder(map.get("orderid").toString());
			
			if(CommonUtil.isNotNullOrEmpty(newOrder) && newOrder.getLastState()!=1009){
			
				order.setRealPrice(newOrder.getRealPrice());
				
				status = newOrder.getLastState();
				
				order.setLastState(status);
				
			}else{
				
				order.setLastState(state);
				
			}
		}
		
		addNewNotice(map);
		
		switch (status) {
		// 充值成功
		case 2:
			if (order.getLastState() == status) {
				success(order);
			}
			break;
		// 部分成功
		case 3:
			if (order.getLastState() == status) {
				partialSuccess(order);
			}
			break;
		// 充值失败
		case 4:
			if (order.getLastState() == status) {
				failure(order);
			}
			break;
		// 退货
//		case 9:
//			order.setSalePrice(Double.parseDouble(map.get("ordermoney")
//						.toString()));
//			refund(order);
//			break;
		}
		LOG.info("[" + order.getOrderid() + "]面额：" + order.getProPrice()
				+ ";充值状态：" + status + ";完成金额：" + order.getRealPrice());
	}

	/**
	 * 获取存在的订单数据信息
	 */
	public Order searchOrder(String orderid) {

		DBHelper dh = DBHelper.getInstance();

		dh.setBeanClass(Order.class);

		Order order = null;

		try {
			order = (Order) dh
					.query("SELECT * FROM Mobile_Record WITH(NOLOCK) WHERE orderId='"
							+ orderid + "'");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dh.close();
		return order;
	}

	/**
	 * 添加新通知
	 * 
	 * @param map
	 */
	public void addNewNotice(Map map) {
		String sql = "{call addMobileNotice(?,?,?,?)}";

		Object[] args = new Object[4];

		args[0] = map.get("orderid");

		args[1] = map.get("status");

		args[2] = map.get("ordermoney");

		args[3] = map.get("verifystring") != null ? map.get("verifystring")
				: "ERROR";

		update(sql, args);

	}

	private void goPayNotice(Order order, String salePrice, String desc,
			int type) {

		IPayToApi aliPay = new PayToApi();

		PayEntity pe = new PayEntity();

		pe.setTot_trans_amt(salePrice);

		pe.setOrderid(order.getOrderid());

		pe.setBuyer_id(order.getMemberNo());

		pe.setSeller_id(GlobalVariables.MOBILE_SELLER_ID);

		pe.setSub_order_flag("N");

		pe.setSub_order_num(0);

		pe.setOrder_desc(desc);

		pe.setMobileRealPrice(order.getRealPrice());

		pe.setOrder_CreateTime(CommonUtil.returnDateToString(order
				.getDateTime()));
		
		
		pe.setNotify_url(PropertiesManager.getInstance().returnValue(
				"PAY_MOBILE_NOTICE"));
		switch (type) {
		case 1:
			// 预授权完成
			aliPay.YSQWC(pe);
			break;
		case 2:
			// 预授权撤销
			aliPay.YSQCX(pe);
			break;
		case 3:
			// 退货
			aliPay.REFUND(pe);
			break;
		}

	}

	private int update(String strSql, Object... args) {

		int count = 0;

		DBHelper dh = DBHelper.getInstance();

		try {

			count = dh.update(strSql, args);

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			LOG.error(new StringBuffer("操作数据时异常").append(e.getMessage())
					.append("\n").append("执行语句：").append(strSql).append("\n")
					.append("参数信息：").append(args));

			LOG.error(strSql);

			e.printStackTrace();
		} finally {

			dh.close();

			return count;

		}

	}

	/**
	 * 充值成功
	 */
	public void success(Order order) {

		String salePrice = (new String()
				.valueOf((int) (order.getSalePrice() * 100)));

		String desc = returnOrderDesc(order.getOrderid(), "充值成功[" + salePrice
				+ "]，预授权完成");

		goPayNotice(order, salePrice, desc, 1);

	}

	/**
	 * 部分成功订单
	 */
	public void partialSuccess(Order order) {

		String salePrice = returnSalePriceForPay(order);
		String desc = returnOrderDesc(order.getOrderid(), "部分充值成功[" + salePrice
				+ "]，预授权完成");

		goPayNotice(order, salePrice + "", desc, 1);

	}

	/**
	 * 充值失败
	 * 
	 * @param strSql
	 */
	public void failure(Order order) {
		String salePrice = new String()
				.valueOf((int) (order.getSalePrice() * 100));

		String desc = returnOrderDesc(order.getOrderid(), "充值失败，撤销金额["
				+ order.getSalePrice() + "]，预授权撤销");

		goPayNotice(order, salePrice, desc, 2);

	}

	public void refund(Order order) {
		String salePrice = new String()
				.valueOf((int) (order.getSalePrice() * 100));

		String desc = returnOrderDesc(order.getOrderid(), "充值失败，退款["
				+ order.getSalePrice() + "]，订单退货");

		goPayNotice(order, salePrice, desc, 3);

	}

	/**
	 * 添加部分充值记录
	 * 
	 * @param mp
	 */
	private void addMobilePar(MobilePar mp) {
		String sql = "{call addMobilePar(?,?,?)}";

		Object[] args = new Object[3];

		args[0] = mp.getOrderid();

		args[1] = mp.getOrdermoney();

		args[2] = mp.getSalePrice();

		update(sql, args);

	}

	/**
	 * 返回部份充值应支付金额
	 * 
	 * @param order
	 * @return
	 */
	private String returnSalePriceForPay(Order order) {
		int num = (int) ((float) order.getSalePrice() / order.getProPrice()
				* order.getRealPrice() * 100);
		return (int) (((float) num / 100) * 100) + "";
	}

	private String returnOrderDesc(String orderId, String desc) {
		return new StringBuffer("[").append(orderId).append("]").append(desc)
				.toString();
	}
}
